//
//  ETH+Transaction+RPC.swift
//  XHWalletUtils
//
//  Created by xinph on 2020/5/20.
//  Copyright © 2020 xinph. All rights reserved.
//

import Foundation

extension ETH: TransactionRPCProtocol {
    public func writeContract(_ from: AddressConvertible, to: AddressConvertible, money: String, password: String, closure: @escaping (Result<TransactionSendingResult>) -> Void) {
        guard let web3 = self.generateWeb3() else { return }
        let value: String = money
        let walletAddress = EthereumAddress(from.asAddress())! // Your wallet address
        let toAddress = EthereumAddress(to.asAddress())!
        let contract = web3.contract(Web3.Utils.coldWalletABI, at: toAddress, abiVersion: 2)!
        let amount = Web3.Utils.parseToBigUInt(value, units: .eth)
        var options = TransactionOptions.defaultOptions
        options.value = amount
        options.from = walletAddress
        options.gasPrice = .automatic
        options.gasLimit = .automatic
        let transaction = contract.write(
            "fallback",
            parameters: [AnyObject](),
            extraData: Data(),
            transactionOptions: options)!
        transaction.sendPromise(password: password, transactionOptions: options)
            .done { (rst) in
                closure(Result.success(rst))
        }.catch { (err) in
            closure(Result.failure(XHError(err: err)))
            print(err)
        }.finally {
            //关闭菊花
        }
    }

    public func getTransactionDetails(_ txhash: String, closure: @escaping (Result<TransactionDetails>) -> Void) {
        guard let web3 = self.generateWeb3() else { return }
        web3.eth.getTransactionDetailsPromise(txhash)
            .done { (rst) in
                closure(Result.success(rst))
        }.catch { (err) in
            closure(Result.failure(XHError(err: err)))
            print(err)
        }.finally {
            //关闭菊花
        }
    }
}
